<?php

use Illuminate\Support\Facades\Route;

if (!function_exists('get_ip')) {
    /**
     * 获取真实的IP地址
     *
     * @param void
     * @return string
     */
    function get_ip() : string
    {
        if (getenv('HTTP_X_REAL_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_REAL_FORWARDED_FOR'),'unknown')) {
            $ip = getenv('HTTP_X_REAL_FORWARDED_FOR');
        } else if (getenv('HTTP_X_FORWARDED_FOR') && strcasecmp(getenv('HTTP_X_FORWARDED_FOR'),'unknown')) {
            $ip = getenv('HTTP_X_FORWARDED_FOR');
        } else if (getenv('HTTP_CLIENT_IP') && strcasecmp(getenv('HTTP_CLIENT_IP'),'unknown')) {
            $ip = getenv('HTTP_CLIENT_IP');
        } else if (getenv('REMOTE_ADDR') && strcasecmp(getenv('REMOTE_ADDR'),'unknown')) {
            $ip = getenv('REMOTE_ADDR');
        } else if (filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP)) {
            $ip = filter_input(INPUT_SERVER, 'REMOTE_ADDR', FILTER_VALIDATE_IP);
        }
        $ip = preg_replace("/^([\d\.]+).*/","\\1", $ip);

        return $ip;
    }
}

if (!function_exists('get_current_action')) {
    /**
     * 获取当前请求的控制器@方法
     *
     * @param void
     * @return array
     */
    function get_current_action() : array
    {
        $current = Route::current()->getActionName();
        list($class, $method) = explode('@', $current);

        return ['controller' => $class, 'action' => $method];
    }
}

if (!function_exists('image_thumb')) {
    function image_thumb($image_url, $width = 64, $height = 64)
    {
        if (false != strpos($image_url, 'image.php')) {
            $image_url_row = explode('!', $image_url);
            $image_url = $image_url_row[0];
            $ext_row = pathinfo($image_url);
            $ext_name = isset($ext_row['extension']) ? $ext_row['extension'] : 'jpg';
            return sprintf('%s!%dx%d.%s', $image_url, $width, $height, $ext_name);
        } else {
            return $image_url;
        }
    }
}